<template>
  <div class="window-page">
    <div>
      <Breadcrumb
        style="margin-right: 20px;"
        @deleteOtherRoute="deleteOtherRouteMethods"
        ref="BreadcrumbRef"
      ></Breadcrumb>
      <FileContentSearchHeader
        :need-list="['search', 'addButton', 'delete']"
        :searchList="['mediaName']"
        @addNewFold="addNewFold"
        add-button-text="添加"
        @startUploadFile="startUploadFile"
        @changeSearch="changeSearchMethods"
        @mutiSendFile="mutiSendFileMethods"
        @mutiDel="windowDelMuti"
      >
        <template slot="media-input">
          <el-input
            placeholder="搜索布局名称"
            suffix-icon="el-search"
            @keyup.native.enter="changeSearchMethods"
            v-model="searchObj.title">
          </el-input>
        </template>
      </FileContentSearchHeader>
    </div>

    <CommonTable
      class="commonTable"
      ref="windowLayoutRef"
      :is-selection="true"
      :is-show-index="true"
      :is-has-opera="true"
      :t-column-data="globalSceneCol"
      :remote-api="getLayoutList"
      :query-params="searchObj"
      :is-reserve-select="true"
      @changeRow="changeRowMethods"
    >
      <template slot="media_name" slot-scope="scope">
        <!--文件夹-->
        <div
          class="file-name-row"
          :ref="`dragBlock${scope.$index}`"
          v-if="scope.row.file_type == '1'"
          :data-id="scope.row.id"
          @click="goToNextFold(scope.row)"
          @drop="(ev) => {dropNewHandler(ev, scope.row)}"
          @dragenter.prevent
          @dragover.prevent
        >
          <img src="../distribute/images/folder.png" class="file-icon" alt="">
          <span :data-id="scope.row.id" :class="scope.row.file_type == '1'?'fold-class': ''">
            {{scope.row.noSuffixMediaName}}
          </span>
        </div>

        <div
          class="file-name-row"
          :ref="`dragBlock${scope.$index}`"
          :draggable="true"
          :data-id="scope.row.id"
          v-else
          @dragstart="dragstartMethods(scope.row)"
          @click="goToNextFold(scope.row)"
        >
          <img src="@/assets/scene/layout.png" class="file-icon" alt="">
          <span :data-id="scope.row.id">
            {{scope.row.title}}
          </span>
        </div>
      </template>
      <template slot="media_type" slot-scope="scope">
        {{scope.row.file_type == '1'? '文件夹': `${scope.row.type == 1?'固定': '自定义'}`}}
      </template>
      <template slot="operate" slot-scope="scope" class="operate-btn">
        <el-button type="text" @click="moveLayout(scope.row, 1)">上移</el-button>
        <el-button type="text" @click="moveLayout(scope.row, 2)">下移</el-button>
        <el-button type="text" v-if="scope.row.id > 4" @click="editLayout(scope.row)">编辑</el-button>
        <el-button type="text" class="del-button" v-if="scope.row.id > 4" @click="showDelWindowWarn(scope.row)">删除</el-button>
<!--        <el-button v-if="$route.query.parentId && scope.row.file_type != 1" type="text" @click="moveToPrevParent(scope.row)">移动至根目录</el-button>-->
      </template>
    </CommonTable>


    <el-dialog
      :title="isEdit ? '编辑' : '窗口布局'"
      :visible.sync="editLayoutForm"
      width="60%"
      :before-close="handleClose">
      <div v-if="editLayoutForm">
        <template v-if="step == 1">
          <div class="window-button">
            <el-button @click="createNewWindow">新建窗口</el-button>
            <el-button @click="delWindowMethods">删除窗口</el-button>
          </div>

          <div class="window-block-container" id="window-block-container">
            <div class="window-block-children"></div>
            <div class="window-block-row" v-for="(item, index) in parseInt(windowLayout.row)">
              <div
                :style="`width: ${Math.floor(800/windowLayout.col) - 1}px;height: ${Math.floor(450/windowLayout.row)+ 1}px`"
                class="window-block-col"
                v-for="(item, index) in parseInt(windowLayout.col)"
              ></div>
            </div>
          </div>

          <el-form :inline="true" class="demo-form-inline row-control">
            <el-form-item label="行数">
              <el-input type="number" v-model="windowLayout.row"></el-input>
            </el-form-item>
            <el-form-item label="列数">
              <el-input v-model="windowLayout.col"></el-input>
            </el-form-item>
          </el-form>
        </template>

        <template v-else-if="step == 2">
          <el-form ref="form" :model="layoutForm" label-width="80px">
            <el-form-item label="布局名称">
              <el-input v-model="layoutForm.title"></el-input>
            </el-form-item>
            <el-form-item label="缩略图">
              <el-upload
                v-if="!layoutForm.image"
                style="width: 100%;"
                class="upload-demo"
                ref="upload"
                drag
                :on-success="uploadSuccess"
                :action="uploadUrl"
              >
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              </el-upload>

              <div v-else>
                <el-image
                  style="width: 100px; height: 100px"
                  :src="layoutForm.image"
                  :preview-src-list="[layoutForm.image]">
                </el-image>
                <div>
                  <el-button @click="clearImage" type="text" class="del-button">删除</el-button>
                </div>
              </div>
            </el-form-item>
          </el-form>
        </template>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button v-if="step == 2" type="primary" @click="preStep">上一步</el-button>
        <el-button type="primary" @click="confirmSubmitLayout">下一步</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="提示"
      :visible.sync="delWindowDialog"
      width="30%"
      :before-close="handleClose">
      <div>
        是否要删除窗口
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="confirmDelWindowForm">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="编辑"
      :visible.sync="editWindowDialog"
      width="30%"
      :before-close="handleClose">
      <el-form ref="form" :model="layoutForm" label-width="80px">
        <el-form-item label="布局名称">
          <el-input v-model="layoutForm.title"></el-input>
        </el-form-item>
        <el-form-item label="缩略图">
          <el-upload
            v-if="!layoutForm.image"
            style="width: 100%;"
            class="upload-demo"
            drag
            :on-success="uploadSuccess"
            :action="uploadUrl"
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          </el-upload>

          <div v-else>
            <el-image
              style="width: 100px; height: 100px"
              :src="layoutForm.image"
              :preview-src-list="[layoutForm.image]">
            </el-image>
            <div>
              <el-button @click="clearImage" class="del-button" type="text">删除</el-button>
            </div>
          </div>
        </el-form-item>

<!--        <el-form-item label="坐标">-->
<!--          <el-input v-model="layoutForm.coordinate"></el-input>-->
<!--        </el-form-item>-->
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="confirmEditWindowForm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Vue from 'vue/dist/vue.js'
import Mixins from "../distribute/mixins/mixins";
import VueDragResize from 'vue-drag-resize'
import {globalSceneCol} from "@/views/scene/tableCol/globalSceneCol";
import html2Canvas from 'html2canvas'
import request from '@/utils/request'
import * as service from './service'
import {saveWindowLayout} from "./service";

export default {
  mixins: [Mixins],
  components: {
    VueDragResize
  },
  data() {
    return {
      layoutForm: {
        title: '',
        image: ''
      },
      canvasUrl:'',
      editWindowDialog: false,
      uploadUrl: window.ajaxUploadUrl + '/common/fileApi/file',
      windowLayout: {
        row: 3,
        col: 3
      },
      globalSceneCol,
      getLayoutList: service.getLayoutList,
      searchObj: {
        title: '',
        type: ''
      },
      editLayoutForm: false,
      step: 1,
      createWindowNum: 0,
      windowLayoutSaveListCache: [],
      currentDragDom: {},
      delWindowDialog: false,
      mutiDelList: [],
      clickCache: {},
      isEdit:false,
    }
  },
  mounted() {
    this.getWindowLayoutList()
  },
  methods: {

    windowDelMuti() {
      if(this.mutiDelList.length === 0) {
        this.$message.error('请选择要删除场景')
        return
      }
      this.delWindowDialog = true
    },
    showDelWindowWarn(row) {
      this.clickCache = {
        ...row
      }
      this.delWindowDialog = true
    },
    clearImage() {
      this.layoutForm.image = ''
    },
    moveLayout(row, state) {
      const params = {
        id: row.id,
        state
      }

      service.moveWindowLayout(params).then(() => {
        this.$message.success('移动成功')
        this.getWindowLayoutList()
      })
    },
    uploadSuccess(res) {
      console.log('res', res)
      this.layoutForm.image = res.data[0].file
    },
    delWindowMethods() {
      console.log('currentDragDom', this.currentDragDom)
      let currentWindowNum = this.currentDragDom.childNodes[0].innerHTML;
      if(Object.keys(this.currentDragDom).length === 0) {
        this.$message.error('请选择要删除的窗口')
        return
      }
      this.currentDragDom.remove()
      this.currentDragDom = {}

      const contentNodes = document.querySelectorAll('.content-container');
      //生成缩略图时清空分割线
      contentNodes.forEach((contentNode) => {
        if(contentNode.innerHTML > currentWindowNum) {
          contentNode.innerHTML = contentNode.innerHTML - 1;
        }
      })
      this.createWindowNum = this.createWindowNum - 1;
    },
    editLayout(row) {
      console.log('row', row)
      this.step = 1
      this.isEdit = true
      this.layoutForm.title = row.title
      this.layoutForm.image = row.image
      this.layoutForm.id = row.id
      this.layoutForm.horizontal = row.horizontal
      this.layoutForm.vertical = row.vertical
      this.layoutForm.windows = row.windows
      this.createWindowNum = row.windows[row.windows.length - 1]?.sort
      this.editLayoutForm = true
      this.$nextTick(()=> {
        row.windows.forEach(item => {
          console.log('item', item)
          this.createNewWindow('edit', item)
        })
      })
      // this.editWindowDialog = true

    },
    createNewWindow(text, item) {
      console.log('text', text)
      console.log('item', item)
      const _this = this
      let showText = text === 'edit' ? item.sort : _this.createWindowNum + 1
      const windowLayoutContainer = document.querySelector('.window-block-container')
      const windowDom = document.createElement('div')
      windowDom.setAttribute('class', 'new-window-container')
      windowDom.setAttribute('id', 'window-container-' + new Date().getTime())
      windowLayoutContainer.appendChild(windowDom)
      // 定义组件
      const MyComponent = Vue.extend({
        components: {
          VueDragResize
        },
        methods: {
          isActive(str){
            const regex = /^active$/;
            return regex.test(str);
          },
          clickDragMethods(index) {
            // const allDragDom = document.querySelectorAll('.new-window-container')
            // for(let i = 0;i < allDragDom.length; i++) {
            //   let styleStr = allDragDom[i].getAttribute('class')
            //   console.log('styleStr', styleStr)
            //   if(this.isActive(styleStr)) {
            //     _this.currentDragDom = allDragDom[i]
            //   }
            // }
            _this.currentDragDom = this.$refs.drag.$el
            console.log('_this.currentDragDom', _this.currentDragDom)

          },
          startDragging(newRect) {
            console.log('newRect ---', this.currentDragDom)
          },
          // 双击贴边
          doubleClickMethod(){
            _this.currentDragDom = this.$refs.drag.$el
            this.$nextTick(()=> {
              //手动修改ref的值，因为源码中宽度是通过left和right计算出来的，所以left和right都需要修改
              let parentWidth = this.$refs.drag.parentWidth
              let width = this.$refs.drag.width
              console.log('width', width)
              // this.$refs.drag.left = 0
              // this.$refs.drag.right = parentWidth - width

              //行数
              const row = _this.windowLayout.row
              //列数
              const col = _this.windowLayout.col
              const containerWidth = 800;
              const containerHeight = 450;
              // console.log("teststest",rect)
              const drag = this.$refs.drag;
              const dragLeft = drag.left;
              const dragTop = drag.top;
              const dragRight = drag.right;
              const dragBottom = drag.bottom;
              const perWidth = containerWidth / col;
              const perHeight = containerHeight / row;
              //计算左侧覆盖的格子位于第几列
              let newLeftCol = [];
              let newLeftColSame  = false;
              for(let i = 0; i <= col; i++){
                if(perWidth * i > dragLeft) {
                  // newLeftCol = i - 1;
                  newLeftCol.push(i - 1)
                  break;
                }
                if(perWidth * i == dragLeft) {
                  newLeftColSame = true;
                  break;
                }
              }
              if(!newLeftColSame) {
                let max = newLeftCol[newLeftCol.length-1];
                this.$refs.drag.left = perWidth * max;
              }
              //计算右侧覆盖的格子位于第几列
              let newRightCol = 0;
              let newRightColSame  = false;
              for(let i = 0; i <= col; i++){
                if(perWidth * i > (containerWidth - dragRight)) {
                  newRightCol = i;
                  break;
                }
                if(perWidth * i == (containerWidth - dragRight)) {
                  newRightColSame  = true;
                  break;
                }
              }
              if(!newRightColSame) {
                this.$refs.drag.right = containerWidth - perWidth * newRightCol;
              }
              //计算上面覆盖的格子位于第几行
              let newTopRow = [];
              let newTopRowSame = false;
              for(let i = 0; i <= row; i++){
                if(perHeight * i > dragTop) {
                  newTopRow.push(i - 1);
                  break;
                }
                if(perHeight * i == dragTop) {
                  newTopRowSame = true;
                  break;
                }
              }
              if(!newTopRowSame) {
                let max = newTopRow[newTopRow.length-1];
                this.$refs.drag.top = perHeight * max;
              }
              //计算下面覆盖的格子位于第几行
              let newBottomRow = 0;
              let newBottomRowSame = false;
              for(let i = 0; i <= row; i++){
                if(perHeight * i > (containerHeight - dragBottom)) {
                  newBottomRow = i;
                  break;
                }
                if(perHeight * i == (containerHeight - dragBottom)) {
                  newBottomRowSame = true;
                  break;
                }
              }
              if(!newBottomRowSame) {
                this.$refs.drag.bottom = containerHeight - perHeight * newBottomRow;
              }


            })
          },
          //回显方法
          echoMethod(){
            console.log('parentHeight', this.$refs.drag.parentHeight)
            console.log('parentWidth', this.$refs.drag.parentWidth)
            // 计算 top 值
            if(_this.isEdit){
              if(item.coordinate != undefined && item.coordinate != null) {
                item.coordinate = typeof item.coordinate === 'string' ? JSON.parse(item.coordinate) : item.coordinate
              }
            }
            if(item.coordinate != undefined && item.coordinate != null) {
              const topValue = (parseFloat(item.coordinate.top.replace('%', '')) / 100) * 450;
              const leftValue = (parseFloat(item.coordinate.left.replace('%', '')) / 100) * 800;
              const width = (parseFloat(item.coordinate.width.replace('%', '')) / 100) * 800
              const height = (parseFloat(item.coordinate.height.replace('%', '')) / 100) * 450
              this.$refs.drag.top = topValue
              this.$refs.drag.bottom = this.$refs.drag.parentHeight - topValue - height
              this.$refs.drag.left = leftValue
              this.$refs.drag.right = this.$refs.drag.parentWidth - leftValue - width
              console.log(this.$refs.drag)
            }
          },
        },
        template: `<vue-drag-resize ref="drag" @dragstop="startDragging" @dblclick.native="doubleClickMethod" :w="50" :h="50" :x="0" :y="0" @clicked="clickDragMethods" data-index="${parseInt(this.createWindowNum, 10) + 1}" class="new-window-container" :parentLimitation="true">${showText}</vue-drag-resize>`
      });

      // 创建组件实例
      const componentInstance = new MyComponent();
      console.log('componentInstance', componentInstance)

      // 挂载到DOM元素上
      componentInstance.$mount(windowDom);
      if(text !== 'edit'){
        this.createWindowNum += 1
      }else{
        componentInstance.echoMethod()
      }
    },
    changeRowMethods(rows) {
      this.mutiDelList = [...rows]
    },
    handleClose() {
      this.editLayoutForm = false
      this.delWindowDialog = false
      this.editWindowDialog = false
      this.layoutForm = {
        title: '',
        image: ''
      }
      this.createWindowNum = 0
      this.step = 1
      this.windowLayoutSaveListCache = []
    },
    confirmEditWindowForm() {
      const params = {
        ...this.layoutForm,
        horizontal: this.windowLayout.row,
        vertical: this.windowLayout.col,
        windows: [...this.windowLayoutSaveListCache]
      }
      params.windows.forEach((item) => {
        delete item.layout_id
      })
      params.windows.forEach((item) => {
        item.coordinate = JSON.stringify(item.coordinate)
      })
      service.saveWindowLayout(params).then(() => {
        this.$message.success('编辑成功')
        this.editWindowDialog = false
        this.getWindowLayoutList()
        this.createWindowNum = 0
      })
    },
    confirmDelWindowForm() {
      this.delService()
    },
    delService() {
      if(this.mutiDelList.length > 0) {
        const params = {
          ids: []
        }
        this.mutiDelList.forEach((item) => {
          params.ids.push(item.id)
        })

        service.delWindowLayout(params).then(() => {
          this.$message.success('删除成功')
          this.getWindowLayoutList()
          this.delWindowDialog = false
          this.mutiDelList = []
        })
      } else {
        const params = {
          ids: [this.clickCache.id]
        }
        service.delWindowLayout(params).then(() => {
          this.$message.success('删除成功')
          this.getWindowLayoutList()
          this.delWindowDialog = false
          this.clickCache = {}
        })
      }
    },
    //上一步回显
    preStep(){
      this.layoutForm.image = null;
      this.step -= 1
      this.$nextTick(()=> {
        this.windowLayoutSaveListCache.forEach(item => {
          this.createNewWindow('edit', item)
        })
      })
    },
    async confirmSubmitLayout() {
      if(this.step == 1) {
        if(this.createWindowNum === 0) {
          this.$message.error('请新建窗口')
          return
        }
        const windowLayoutList = document.querySelectorAll('.new-window-container')
        console.log('windowLayoutList', windowLayoutList)
        this.windowLayoutSaveListCache = []
        for(let i = 0;i < windowLayoutList.length;i++) {
          let rect = windowLayoutList[i].getBoundingClientRect()
          let styleStr = windowLayoutList[i].getAttribute('style')
          let styleList = []
          if(styleStr.indexOf(';')) {
            styleList = styleStr.split(';')
          }

          let leftNumber = 0
          let topNumber = 0
          styleList.forEach((item) => {
            if(item.indexOf('left:') !== -1) {
              leftNumber = parseFloat(item.replaceAll('left:', '').replaceAll('px', '').trim())
            }
            if(item.indexOf('top:') !== -1) {
              topNumber = parseFloat(item.replaceAll('top:', '').replaceAll('px', '').trim())
            }
          })

          // 父容器固定长，宽450px 计算滑块的百分比 方便适配不能写死像素
          let top = parseFloat((topNumber/450) * 100).toFixed(2);
          let left = parseFloat((leftNumber/800) * 100).toFixed(2);
          let width = parseFloat((rect.width/800) * 100).toFixed(2);
          let height = parseFloat((rect.height/450) * 100).toFixed(2);
          if(top > 100) {
            top = 100;
          }
          if(left > 100) {
            left = 100;
          }
          if(width > 100) {
            width = 100;
          }
          if(height > 100) {
            height = 100;
          }
          let tmp = {
            coordinate: {
              // top: '',
              top: `${top}%`,
              left: `${left}%`,
              // width: rect.width + 'px',
              width: `${width}%`,
              // height: rect.height + 'px',
              height: `${height}%`,
            },
            sort: windowLayoutList[i].innerText
          }
          this.windowLayoutSaveListCache.push(tmp)
          console.log('tmp ---', tmp)
        }
        this.step += 1
        //没有缩略图的话，默认剪切拖拽dom到canvas并导出图片
        if(!this.layoutForm.image){

          const colNodes = document.querySelectorAll('.window-block-col');
          //生成缩略图时清空分割线
          colNodes.forEach((colNode) => {
            colNode.style.border= 'none';
          })
          let cloneDom = document.querySelector('#window-block-container')
          cloneDom.style.border = 'none';
          console.log('cloneDom', cloneDom)
          let opts = {
            backgroundColor: null
          }
          const canvasDom = await html2Canvas(cloneDom, opts)
          this.canvasUrl = canvasDom.toDataURL('image/png')
          this.layoutForm.image = this.canvasUrl
        }else{
          this.canvasUrl = ''
        }
      } else if(this.step == 2) {
        if(this.canvasUrl){
          //如果缩略图是默认的canvas图片需要走上传接口
          const file = this.dataURLtoFile(this.canvasUrl, '缩略图.png')
          console.log('file', file)
          const formData = new FormData();
          formData.append('file', file);
          let imageUrlRes = await request.post(
            '/common/fileApi/file',
            formData,
            {
              headers: {
                'Content-Type': 'multipart/form-data'
              }
            },
          )
          console.log('imageUrlRes', imageUrlRes)
          if(imageUrlRes.code === 200){
            this.layoutForm.image = imageUrlRes.data[0].file
            console.log('this.layoutForm.image',  this.layoutForm.image)
          }
        }
        if(this.isEdit){
          //编辑
          this.confirmEditWindowForm()
          this.editLayoutForm = false
        }else{
          const params = {
            ...this.layoutForm,
            horizontal: this.windowLayout.row,
            vertical: this.windowLayout.col,
            windows: [...this.windowLayoutSaveListCache]
          }

          params.windows.forEach((item) => {
            item.coordinate = JSON.stringify(item.coordinate)
          })
          console.log('params', params)
          service.saveWindowLayout(params).then(() => {
            this.$message.success('保存成功')
            this.editLayoutForm = false
            this.getWindowLayoutList()
            this.layoutForm.title = ''
            this.layoutForm.image = ''
            this.step = 1
            this.createWindowNum = 0
            this.windowLayoutSaveListCache = []
          })
        }
      }
    },
    dataURLtoFile(dataurl, filename) {
      let arr = dataurl.split(',');
      let mime = arr[0].match(/:(.*?);/)[1];
      let bstr = atob(arr[1]);
      let n = bstr.length;
      let u8arr = new Uint8Array(n);

      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], filename, { type: mime });
    },
    getWindowLayoutList() {
      const params = Object.assign({}, this.searchObj)
      this.$refs.windowLayoutRef.queryData(params)
    },
    addNewFold() {

    },
    startUploadFile() {
      this.isEdit = false
      this.editLayoutForm = true
    },
    changeSearchMethods() {
      this.getWindowLayoutList()
    }
  }
}
</script>

<style scoped lang="scss">
  .window-page{
    padding: 15px;
    background: white;

    .commonTable{
      margin-top: 15px;
    }

    .window-button{
      width: 100%;
      text-align: center;
    }
    .window-block-container{
      position: relative;
      width: 800px;
      border: 1px solid #F2F6FC;
      min-height: 450px;
      margin: 15px auto 0 auto;
      .window-block-row{
        width: 100%;
        display: flex;
        flex-wrap: wrap;
        .window-block-col {
          border: 1px dashed #000000;
          height: 80px;
        }
      }
    }
  }

  .row-control{
    margin-top: 15px;
    text-align: center;
  }
</style>

<style>
.new-window-container{
  position: absolute;
  top: 0;
  left: 0;
  z-index: 3000;
  background: linear-gradient( 180deg, #61AFFF 0%, #2F71F2 100%);
}
.content-container{
  /* border: 1px solid; */
}
</style>
